<template>
  <el-select
    class="width_100"
    placeholder="请选择"
    v-model="selectValue"
    filterable
    collapse-tags
    collapse-tags-tooltip
    :clearable="clearable"
    :filter-method="handleQuerySearch"
    @change="handleQueryChange"
    @visible-change="visibleChange"
  >
    <el-option
      v-for="item in selectOptions"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
    <ElSelectLoading
      :page="page"
      :loading="loading"
      :hasMore="hasMore"
      @loadMore="handleLoadMore"
    />
  </el-select>
</template>
<!-- 
  下拉筛选【滚动加载更多】【针对于大数量下拉值，以免数据多，页面卡顿】
 -->
<script setup>
  /**
   * @import
   */
  import { getCurrentInstance, ref } from "vue";
  import ElSelectLoading from "/@/components/ElSelectLoading";
  import TestJson from "./test.json";
  import _ from "lodash";

  /**
   * @props
   */
  const props = defineProps({
    // 值
    value: {
      type: String,
      default: "",
    },
    // 类型
    type: {
      type: String,
      default: "name", // number, name, assistant_id, barcode
    },
    // 多选
    multiple: {
      type: Boolean,
      default: false,
    },
    // 一键清除
    clearable: {
      type: Boolean,
      default: true,
    },
  });

  /**
   * @var
   */

  const proxy = getCurrentInstance()?.proxy;
  const page = ref(0);
  const loading = ref(false);
  const hasMore = ref(true);

  const selectValue = ref();
  const sreachValue = ref("");
  const selectOptions = ref([]);

  const emit = defineEmits(["LazyChange"]);

  /**
   * 加载数据列表
   */

  const loadDataList = _.debounce(async () => {
    try {
      loading.value = true;

      // 参数
      let data = {
        page: page.value,
        limit: 10,
        filter: {
          name:
            props.type == "" || props.type == "name" ? sreachValue.value : "", // 物料名称
          number: props.type == "number" ? sreachValue.value : "", // 物料编码
          barcode: props.type == "barcode" ? sreachValue.value : "", // 条码
          use_org_id: props.userOrgId || "", // 使用组织
        },
      };

      // api
      const res = await TestJson;

      // 遍历获取
      const list =
        res.data.list.map((item) => {
          // 复合查询
          if (!props.type)
            return {
              ...item,
              value: item.number,
              label: `${item.number}-${item.name}`,
            };
          if (props.type == "name")
            return { ...item, value: item.name, label: item.name };
          if (props.type == "number")
            return { ...item, value: item.number, label: item.number };
          if (props.type == "barcode")
            return { ...item, value: item.barcode, label: item.barcode };
        }) || [];

      if (page.value == 1) selectOptions.value = [];

      // 添加新的数据
      selectOptions.value.push(...list);

      // 是否进行加载数据
      hasMore.value = selectOptions.value.length < res.data.count;
    } catch (err) {
      console.error(err);
    } finally {
      loading.value = false;
    }
  }, 500);

  /**
   * 加载更多数据
   */
  const handleLoadMore = _.throttle(async (value) => {
    page.value = await value;
    loadDataList();
  }, 500);

  /**
   * 模糊搜索
   */
  const handleQuerySearch = _.throttle((value) => {
    // 去空格 大小写
    sreachValue.value = value?.trim().toLowerCase();
    page.value = 1;
    // 加载数据
    loadDataList();
  }, 500);

  const visibleChange = (lay) => {
    loadDataList();
  };

  /**
   * change
   */
  const handleQueryChange = (value) => {
    let row = [];
    row = selectOptions.value.filter((item) => {
      if (props.type == "number" && item.number == value) return item;
      if (props.type == "name" && item.name == value) return item;
      if (props.type == "barcode" && item.barcode == value) return item;
      if (!props.type && item.number == value) return item;
    });
    emit("LazyChange", { value, row: row[0] });
  };

  /**
   * @实例
   */

  watch(
    () => props.value,
    (newValue, oldValue) => {
      selectValue.value = newValue;
    },
    { deep: true, immediate: true }
  );

  defineExpose({});
</script>

<style lang="scss" scoped></style>
